package com.peng.sell.aspect;

import com.peng.sell.constant.CookieConst;
import com.peng.sell.constant.RedisConst;
import com.peng.sell.exception.SellerAuthorizeException;
import com.peng.sell.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Pointcut("execution(public * com.peng.sell.controller.Seller*.*(..))"
            +"&& !execution(public * com.peng.sell.controller.SellerUserController.*(..))")
    public void checkPermission(){ }


    @Before("checkPermission()")
    public void doCheckPermission(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Cookie cookie = CookieUtil.get(request, CookieConst.TOKEN);
        if(cookie==null){
            log.warn("cookie中没有token");
            throw new SellerAuthorizeException();
        }
        //redis中取值
        String token = redisTemplate.opsForValue().get(String.format(RedisConst.TOKEN_PREFIX, cookie.getValue()));
        if(token==null){
            log.warn("redis中没有token");
            throw new SellerAuthorizeException();
        }

    }
}
